package com.roc.web.action.merinfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 驳回商户统计
 * 
 * @author ML
 *
 */
@Component
@Scope("prototype")
@Namespace("/windControllSta")
public class MerinfoRejectedAction extends PaginationBaseAction {
	private Logger logger = LogManager.getLogger(MerinfoRejectedAction.class);

	private MerinfoRejectedSearchCondition searchCondition;
	private InputStream excelFile;

	@Autowired
	private IPageService pagenitionService;

	@Autowired
	private IExcelService excelService;

	@Action(value = "merinfoRejectedJsp", results = { @Result(name = "success", location = "/pages/windControllSta/merinfoRejectedJsp.jsp") })
	public String merinfoRejectedJsp() {
		
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		
		return SUCCESS;
		}

	@Action(value = "queryMerinfoRejectedList", results = { @Result(name = "success", location = "/pages/windControllSta/merinfoRejectedJsp.jsp") })
	public String queryMerinfoRejectedList() {
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		
		logger.info("===========查询驳回商户信息统计开始============");
		if (searchCondition == null) {
			searchCondition = (MerinfoRejectedSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new MerinfoRejectedSearchCondition();
			}
		}

		try {
			int rows = pagenitionService.countSQL(searchCondition);
			List<AuditingItem> auditList = new ArrayList<AuditingItem>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				auditList = dealTheSearchRsList(auditList, searchRsList);
			}

			logger.info("rows:" + rows + "    searchRsList.size():"
					+ searchRsList.size());

			getRequest().setAttribute("auditList", auditList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			addActionMessage("当前条件下统计到【" + rows + "】条记录");

			logger.info("===========查询驳回商户信息统计结束============");
		} catch (Exception e) {
			logger.error("查询商户审核驳回信息异常" + e);
		}

		return SUCCESS;
	}

	@Action(value = "exportMerinfoRejectedList", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/windControllSta/merinfoRejectedJsp.jsp") })
	public String exportMerinfoRejectedList() {
		logger.info("===========导出驳回商户信息统计开始============");
		if (searchCondition == null) {
			searchCondition = (MerinfoRejectedSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new MerinfoRejectedSearchCondition();
			}
		}

		try {
			int rows = pagenitionService.countSQL(searchCondition);
			List<AuditingItem> auditList = new ArrayList<AuditingItem>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), rows);
				auditList = dealTheSearchRsList(auditList, searchRsList);
			}

			logger.info("rows:" + rows + "    searchRsList.size():"
					+ searchRsList.size());

			HSSFWorkbook work = excelService.exportRejectedMerinfoList(
					auditList, searchCondition.getStartingDate(),
					searchCondition.getEndDate());

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("===========导出驳回商户信息统计结束============");
		} catch (Exception e) {
			logger.error("导出商户审核驳回信息异常" + e);
			return ERROR;
		}

		return SUCCESS;
	}

	private List<AuditingItem> dealTheSearchRsList(
			List<AuditingItem> auditList, List<Object> searchRsList) {
		if (searchRsList != null && searchRsList.size() > 0) {
			Iterator it = searchRsList.iterator();
			while (it.hasNext()) {
				Object[] obj = (Object[]) it.next();
				AuditingItem ai = new AuditingItem();
				ai.setCreateDate(Constance.Null2EmptyTrim(obj[0]));
				ai.setObj_Audited(Constance.Null2EmptyTrim(obj[1]));
				ai.setBankBelongCd(Constance.Null2EmptyTrim(obj[3]));
				ai.setAuditorName(Constance.Null2EmptyTrim(obj[9]));
				ai.setShortName(Constance.Null2EmptyTrim(obj[5]));
				ai.setMerinfoName(Constance.Null2EmptyTrim(obj[6]));
				ai.setContanctName(Constance.Null2EmptyTrim(obj[7]));
				ai.setContanctPh(Constance.Null2EmptyTrim(obj[8]));
				ai.setAgentName(Constance.Null2EmptyTrim(obj[4]));
				ai.setResult_detail(Constance.Null2EmptyTrim(obj[10]));
				ai.setBranchcompy(Constance.Null2EmptyTrim(obj[11]));
				ai.setOneagent(Constance.Null2EmptyTrim(obj[12]));
				auditList.add(ai);
			}
		}
		return auditList;
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// SEARCH_SESSION_MERINFO_REJECTED
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_MERINFO_REJECTED,
				searchCondition);

	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (MerinfoRejectedSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_MERINFO_REJECTED);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE + "";
	}

	public MerinfoRejectedSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			MerinfoRejectedSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		String excelName = "驳回商户详情" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

	}

}
